package com.mdlib.helper.receiver;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.NotificationCompat;

import com.blankj.utilcode.utils.AppUtils;
import com.google.gson.Gson;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechEvent;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.ljlib.core.util.LogUtil;
import com.ljlib.help.R;
import com.mdlib.helper.common.ContentType;
import com.mdlib.helper.model.AccountModel;
import com.mdlib.helper.module.run.order.activitys.RushOrderDetailsActivity;
import com.mdlib.helper.module.run.profile.activitys.RushBalanceActivity;
import com.mdlib.helper.module.run.profile.activitys.RushMessageActivity;
import com.mdlib.helper.module.send.order.activitys.OrderDetailsActivity;
import com.mdlib.helper.module.send.profile.activitys.BalanceActivity;
import com.mdlib.helper.module.send.profile.activitys.MessageActivity;
import com.mdlib.helper.service.MDPushIntentService;
import com.mdlib.helper.ui.UIHelper;
import com.mdlib.helper.ui.activity.MainActivity;
import com.orhanobut.logger.Logger;
import com.umeng.message.entity.UMessage;

import org.android.agoo.common.AgooConstants;
import org.json.JSONObject;

import java.util.Random;

import cn.jpush.android.api.JPushInterface;


/**
 * Created by librabin on 17/1/11.
 */

public class NotificationReceiver extends BroadcastReceiver {
    private static final String TAG = MDPushIntentService.class.getName();
    private static final String OPEN_TYPE = "open_type";
    private static final String PUSH_TEXT = "text";
    private static final String PUSH_DEFAULT = "你有新的订单，请及时查看";
    private Gson mGson = new Gson();
    private SpeechSynthesizer mTts;
    private String pushText;
    private String roleText;
    private String roleType = AccountModel.getInstance().getRoleType();
    @Override
    public void onReceive(Context context, Intent intent) {
//        String packName = AppUtils.getAppInfo(context).getPackageName();
//
//        Intent launchIntent = context.getPackageManager().
//                getLaunchIntentForPackage(packName);
//        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//        context.startActivity(launchIntent);
        try {

            //可以通过MESSAGE_BODY取得消息体
            String message = intent.getExtras().getString(JPushInterface.EXTRA_MESSAGE);
            UMessage msg = new UMessage(new JSONObject(message));

            JSONObject jsonObject = new JSONObject(msg.custom);

            JSONObject json = new JSONObject(jsonObject.optString("data"));
            Logger.e("推送" + json.toString());
            String title = json.optString("title");
            pushText = json.optString(PUSH_TEXT);
            String openType = json.optString(OPEN_TYPE);
            String busId = json.optString("bus_id");
            roleText = json.optString("role");
            boolean runType = roleType.equals("user") ? true : false;
            boolean runIndex = openType.equals(UIHelper.PUSH_TYPE_RUN_INDEX);
            if (MainActivity.mPushType && runIndex && !runType) {
                LogUtil.d(TAG, " get new SpeechSynthesizer");
                mTts = SpeechSynthesizer.createSynthesizer(context, null);

                mTts.setParameter(SpeechConstant.VOICE_NAME, "xiaoyan"); // 设置发音人
                mTts.setParameter(SpeechConstant.SPEED, "50");// 设置语速
                mTts.setParameter(SpeechConstant.VOLUME, "80");// 设置音量，范围 0~100
                // 设置播放合成音频打断音乐播放，默认为true
                mTts.setParameter(SpeechConstant.KEY_REQUEST_FOCUS, "true");
                mTts.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);//云端
                //          mTts.setParameter(SpeechConstant.TTS_AUDIO_PATH, "./sdcard/iflytek.pcm");
                mTts.startSpeaking(PUSH_DEFAULT, new MySynthesizerListener());
            }
            if (!(runType && runIndex)) {
                LogUtil.e(runIndex + "");
                showNotification(context, title, pushText, openType, busId);
            }

        } catch (Exception e) {
            Logger.e(e.getMessage());
        }
    }
     class MySynthesizerListener implements SynthesizerListener {

        @Override
        public void onSpeakBegin() {
            LogUtil.d(TAG, "start play voice");
        }

        @Override
        public void onSpeakPaused() {
            LogUtil.d(TAG, "pause play voice");
        }

        @Override
        public void onSpeakResumed() {
            LogUtil.d(TAG, "Resume play voice");
        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
                LogUtil.d(TAG, "Resume play voice");
            } else if (error != null) {

            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话 id，当业务出错时将会话 id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话 id为null
            if (SpeechEvent.EVENT_SESSION_ID == eventType) {
                String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
                LogUtil.d(TAG,  "session id =" + sid);
            }
        }
    };

    private void handlePushData(String pushData) {
        try {
            JSONObject jsonObject = new JSONObject(pushData);
            String flag = jsonObject.optString("flag");

            if (flag.equals("2")) {
            }

        } catch (Exception e) {
            Logger.e(e.getMessage());
        }

    }


    /**  parameter context ：上下文
     *             title ：标题
     *             pushText : 推送的内容
     *             opentype :消息的类型
     *   消息通知栏
     */



    private void showNotification(Context context, String title, String pushText, String opentype, String busId) {


        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setContentTitle(title)
                .setContentText(pushText)
                .setSmallIcon(R.mipmap.app_logo)
                .setWhen(System.currentTimeMillis())
                .setAutoCancel(true)
                .setSound(Uri.parse("android.resource://" + context.getPackageName() + "/" +R.raw.get_email_mp3))
                .setContentIntent(selectOpenType(context,opentype,busId));

        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        int id = new Random(System.nanoTime()).nextInt();

        manager.notify(id, builder.build());
    }

    private PendingIntent selectOpenType(Context context, String opentype , String busId) {
        String packName = AppUtils.getAppInfo(context).getPackageName();
        Intent launchIntent = null;
        boolean isRush = roleText.equals("user") ? true : false;
        switch (opentype) {
            case UIHelper.PUSH_TYPE_ACCOUNT_BALANCE:
                if (isRush) {
                    launchIntent = new Intent(context, BalanceActivity.class);
                } else {
                    launchIntent = new Intent(context, RushBalanceActivity.class);
                }

                break;
            case UIHelper.PUSH_TYPE_WEB:
                break;
            case UIHelper.PUSH_TYPE_INDEX:
                launchIntent = context.getPackageManager().
                        getLaunchIntentForPackage(packName);
                break;
            case UIHelper.PUSH_TYPE_ORDER_DETAIL:
                if (isRush) {
                    launchIntent = OrderDetailsActivity.newIntent(context, ContentType.ORDERDETAILS, busId);
                } else {
                    launchIntent = RushOrderDetailsActivity.newIntent(context, busId);
                }
                break;
            case UIHelper.PUSH_TYPE_HISTORY:
                launchIntent = new Intent(context, MainActivity.class);
                launchIntent.putExtra("history", true);
                break;
            case UIHelper.PUSH_TYPE_NOTICE_CENTER:
                if (isRush) {
                    launchIntent = new Intent(context, MessageActivity.class);
                } else {
                    launchIntent = new Intent(context, RushMessageActivity.class);
                }
                break;
            case UIHelper.PUSH_TYPE_RUN_INDEX:
                launchIntent = new Intent(context, MainActivity.class);
                break;
            default:
                launchIntent = context.getPackageManager().
                        getLaunchIntentForPackage(packName);
                break;
        }
        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent pi = PendingIntent.
                getActivity(context, 0, launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        return pi;
    }
}
